package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@RefreshScope
@Slf4j
public class ManageServiceImpl implements ManageService {

    //  调用mapper 操作数据库；操作BaseCategory1 表 创建对应的mapper
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseAttrValueService baseAttrValueService;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private SpuImageService spuImageService;

    @Autowired
    private SpuPosterService spuPosterService;

    @Autowired
    private SpuSaleAttrValueService spuSaleAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImageService skuImageService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuAttrValueService skuAttrValueService;

    @Autowired
    private SpuSaleAttrService spuSaleAttrService;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitService rabbitService;

    //  这种方式叫做软编码
    @Value("${minio.endpointUrl}")
    private String endpointUrl;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secreKey}")
    private String secreKey;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        //  select * from base_category2 where category1_id = 1;
        //  泛型：查询哪个表，就给哪个表对应的实体类
        //        QueryWrapper<BaseCategory2> baseCategory2QueryWrapper = new QueryWrapper<>();
        //        baseCategory2QueryWrapper.eq("category1_id",category1Id);
        //        baseCategory2QueryWrapper.orderByDesc("id");

        //  企业使用较多
        LambdaQueryWrapper<BaseCategory2> baseCategory2LambdaQueryWrapper = new LambdaQueryWrapper<>();
        //  SFunction R apply(T t); 复制小括号，写死右箭头，落地大括号。 想要干啥？
        //        mybatis-plus; 不支持 get,set 开头的方法.
        //        baseCategory2LambdaQueryWrapper.eq(baseCategory2 -> {
        //            return baseCategory2.getCategory1Id();
        //        },category1Id);
        //  baseCategory2LambdaQueryWrapper.eq(baseCategory2 -> baseCategory2.getCategory1Id(),category1Id);
        //  直接就可以获取到BaseCategory2::getCategory1Id 这个数据。
        baseCategory2LambdaQueryWrapper.eq(BaseCategory2::getCategory1Id,category1Id);
        baseCategory2LambdaQueryWrapper.orderByDesc(BaseCategory2::getId);
        return baseCategory2Mapper.selectList(baseCategory2LambdaQueryWrapper);
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        //  select * from base_attr_value where attr_id = ?;
        LambdaQueryWrapper<BaseAttrValue> baseAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseAttrValueLambdaQueryWrapper.eq(BaseAttrValue::getAttrId,attrId);
        return baseAttrValueMapper.selectList(baseAttrValueLambdaQueryWrapper);
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    public String fileUpLoad(MultipartFile file) {
        String url;
        try {
            // 创建一个MinioClient 客户端对象
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(endpointUrl)
                            .credentials(accessKey, secreKey)
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                System.out.println("Bucket "+bucketName+" already exists.");
            }
            //  获取上传文件的名称.
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+ FilenameUtils.getExtension(originalFilename);
            // Upload known sized input stream.
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            //  url 拼接数据： //img10.360buyimg.com/n7/jfs/t1/87400/22/24585/130257/622867baE8f860c00/60574bb382d1cd67.jpg
            //  http://192.168.200.130:9000/atguigus/622867baE8f860c00/60574bb382d1cd67.jpg
            //  为什么要拼接?
            url = endpointUrl+"/"+bucketName+"/"+fileName;
            System.out.println("url:"+url);
        } catch (ErrorResponseException e) {
            throw new RuntimeException(e);
        } catch (InsufficientDataException e) {
            throw new RuntimeException(e);
        } catch (InternalException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidResponseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (XmlParserException e) {
            throw new RuntimeException(e);
        }
        return url;
    }

    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        //  select * from spu_image where spu_id = 8;
        LambdaQueryWrapper<SpuImage> spuImageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        spuImageLambdaQueryWrapper.eq(SpuImage::getSpuId,spuId).orderByDesc(SpuImage::getId);
        return spuImageMapper.selectList(spuImageLambdaQueryWrapper);
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        //  根据spuId 查询销售属性+销售属性值
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    @SneakyThrows
    @Override
    public void onSale(Long skuId) {
        //  延迟双删： 先删除 修改 睡眠 再删除 sku:[21]:info
        String skuKey = RedisConst.SKUKEY_PREFIX+"["+skuId+"]"+RedisConst.SKUKEY_SUFFIX;
        //  删除缓存数据
        this.redisTemplate.delete(skuKey);

        //  is_sale = 1
        SkuInfo skuInfo = new SkuInfo();
        //  赋值
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);
        //  将布隆过滤器中添加skuId
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);
        bloomFilter.add(skuInfo.getId());
        //  发送消息：发送内容谁来决定！消费者：
        rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuInfo.getId());

        //  睡眠：
        Thread.sleep(300);
        this.redisTemplate.delete(skuKey);

    }

    @SneakyThrows
    @Override
    public void cancelSale(Long skuId) {
        //  获取缓存的key
        String skuKey = RedisConst.SKUKEY_PREFIX+"["+skuId+"]"+RedisConst.SKUKEY_SUFFIX;
        //  删除缓存数据
        this.redisTemplate.delete(skuKey);
        //  is_sale = 0
        SkuInfo skuInfo = new SkuInfo();
        //  赋值
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
        //  发送消息：发送内容谁来决定！消费者：
        rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuInfo.getId());
        //  睡眠：
        Thread.sleep(300);
        this.redisTemplate.delete(skuKey);
    }

    @Override
    @GmallCache(prefix = RedisConst.SKUKEY_PREFIX,suffix = RedisConst.SKUKEY_SUFFIX)
    public SkuInfo getSkuInfo(Long skuId) {
        //  声明一个SkuInfo 对象
        return getSkuInfoDB(skuId);
        //  return getInfoByRedissonTryLock(skuId);
        //  return getInfoByRedissonLock(skuId);
        //  return getInfoByRedis(skuId);
    }

    private SkuInfo getInfoByRedissonTryLock(Long skuId) {
        SkuInfo skuInfo = null;
        try {
            //  判断缓存中是否有数据 数据类型：String  key=sku:skuId:info value=SkuInfo;  set key value key/value 都是字符串.
            String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            //  get key;
            skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            //  判断是否为空
            if (skuInfo==null){
                System.out.println("缓存中没有数据.");
                //  声明一个锁的key. sku:skuId:lock
                String locKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                //  使用redisson
                RLock lock = redissonClient.getLock(locKey);
                //  上锁
                boolean res = false;
                try {
                    res = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (res){
                    try {
                        //  执行业务留级
                        skuInfo = this.getSkuInfoDB(skuId);
                        if (skuInfo==null){
                            SkuInfo skuInfo1 = new SkuInfo();
                            //  放入缓存,给一个过期时间.
                            this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                            return skuInfo1;
                        }
                        //  放入缓存
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                        System.out.println("从数据库中获取数据，并将其放入缓存");
                        return skuInfo;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        //  解锁
                        lock.unlock();
                    }
                } else {
                    //  没有获取到锁！
                    return getSkuInfo(skuId);
                }
            }else {
                //  缓存有数据
                System.out.println("从缓存中获取了数据...");
                return skuInfo;
            }
        } catch (RuntimeException e) {
            //  throw new RuntimeException(e);
            log.error("获取数据异常{}",e.getMessage());
        }
        return getSkuInfoDB(skuId);
    }

    private SkuInfo getInfoByRedissonLock(Long skuId) {
        //  声明一个SkuInfo 对象
        SkuInfo skuInfo = null;
        try {
            //  判断缓存中是否有数据 数据类型：String  key=sku:skuId:info value=SkuInfo;  set key value key/value 都是字符串.
            String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            //  get key;
            skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            //  判断是否为空
            if (skuInfo==null){
                System.out.println("缓存中没有数据.");
                //  声明一个锁的key. sku:skuId:lock
                String locKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                //  使用redisson
                RLock lock = redissonClient.getLock(locKey);
                //  上锁
                lock.lock();
                try {
                    //  执行业务留级
                    skuInfo = this.getSkuInfoDB(skuId);
                    if (skuInfo==null){
                        SkuInfo skuInfo1 = new SkuInfo();
                        //  放入缓存,给一个过期时间.
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                        return skuInfo1;
                    }
                    //  放入缓存
                    this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                    System.out.println("从数据库中获取数据，并将其放入缓存");
                    return skuInfo;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //  解锁
                    lock.unlock();
                }
            }else {
                //  缓存有数据
                System.out.println("从缓存中获取了数据...");
                return skuInfo;
            }
        } catch (RuntimeException e) {
            //  throw new RuntimeException(e);
            log.error("获取数据异常{}",e.getMessage());
        }
        return getSkuInfoDB(skuId);
    }

    private SkuInfo getInfoByRedis(Long skuId) {
        //  声明一个SkuInfo 对象
        SkuInfo skuInfo = null;
        try {
            //  判断缓存中是否有数据 数据类型：String  key=sku:skuId:info value=SkuInfo;  set key value key/value 都是字符串.
            String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            //  get key;
            skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            //  判断是否为空
            if (skuInfo==null){
                //  声明一个锁的key. sku:skuId:lock
                String locKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                //  声明一个uuid
                String uuid = UUID.randomUUID().toString();
                //  上锁：
                Boolean result = this.redisTemplate.opsForValue().setIfAbsent(locKey, uuid, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //  判断是否上锁成功
                if (result){
                    //  说明缓存中没有数据.
                    skuInfo = this.getSkuInfoDB(skuId);
                    if (skuInfo==null){
                        SkuInfo skuInfo1 = new SkuInfo();
                        //  放入缓存,给一个过期时间.
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                        //  删除锁
                        delKey(locKey, uuid);
                        return skuInfo1;
                    }
                    //  放入缓存
                    this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                    //  删除锁
                    delKey(locKey, uuid);
                    return skuInfo;
                } else {
                    //  获取锁失败：
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    return getSkuInfo(skuId);
                }

            } else {
                //  说明缓存中有数据
                return skuInfo;
            }
        } catch (RuntimeException e) {
            //  记录异常信息.
            log.error("查看商品详情有异常{}",e.getMessage());
            //  调用发送短信接口.通知运维人员维护.
//            throw new RuntimeException(e);
        }
        //  让数据库先扛一下.
        return getSkuInfoDB(skuId);
    }

    private void delKey(String locKey, String uuid) {
        //  声明一个lua 脚本
        String script ="if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end\n";
        //  创建对象
        DefaultRedisScript defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setScriptText(script);
        defaultRedisScript.setResultType(Long.class);
        //  执行lua 脚本
        this.redisTemplate.execute(defaultRedisScript, Arrays.asList(locKey), uuid);
    }

    private SkuInfo getSkuInfoDB(Long skuId) {
        //  1：skuInfo 基本数据
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo!=null){
            //  2：根据skuId 查询图片列表
            skuInfo.setSkuImageList(skuImageMapper.selectList(new LambdaQueryWrapper<SkuImage>().eq(SkuImage::getSkuId, skuId)));
        }
        //  返回skuInfo 对象
        return skuInfo;
    }

    @Override
    @GmallCache(prefix = "categoryView:",suffix = ":info")
    public BaseCategoryView getCategoryView(Long category3Id) {
        //  select * from base_category_view  where id = 61;
        return this.baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        //  select price from sku_info  where id = 22;
        //  select * from sku_info where id = 22;
        //  SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //  声明一个key
        String locKey = skuId+":price";
        RLock lock = redissonClient.getLock(locKey);
        //  boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
        lock.lock();
        //  获取到锁
        try{
            LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            skuInfoLambdaQueryWrapper.eq(SkuInfo::getId,skuId).select(SkuInfo::getPrice);
            SkuInfo skuInfo = skuInfoMapper.selectOne(skuInfoLambdaQueryWrapper);
            //  返回价格数据
            return skuInfo.getPrice();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            //  解锁
            lock.unlock();
        }
        //  默认给0;
        return new BigDecimal("0");
    }

    @Override
    @GmallCache(prefix = "spuPoster:",suffix = ":info")
    public List<SpuPoster> findSpuPosterBySpuId(Long spuId) {
        //  select * from spu_poster where spu_id = 9;
        return spuPosterMapper.selectList(new LambdaQueryWrapper<SpuPoster>().eq(SpuPoster::getSpuId,spuId));
    }

    @Override
    @GmallCache(prefix = "attr:")
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        //  调用mapper 层
        return baseAttrInfoMapper.selectAttrList(skuId);

    }

    @Override
    public List<SkuAttrValue> getSkuAttrValueList(Long skuId) {
        return skuAttrValueMapper.selectSkuAttrValueList(skuId);
    }

    @Override
    @GmallCache(prefix = "spuSaleAttr:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        //  调用mapper 层
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId,spuId);
    }

    @Override
    @GmallCache(prefix = "skuValueIds:")
    public Map getSkuValueIdsMap(Long spuId) {
        //  声明一个map 集合
        HashMap<Object, Object> map = new HashMap<>();
        //  {"3725|3727":21,"3724|3727":22} map.put(key,value);
        //  skuSaleAttrValueService 它是内置的方法，对多表关联查询sql 支持性差. 使用mapper.
        List<Map> mapList = skuSaleAttrValueMapper.selectSkuValueIdsMap(spuId);
        //  判断集合
        if (!CollectionUtils.isEmpty(mapList)){
            mapList.forEach(map1 -> {
                //  map.put(3725|3727,21); map.put(3724|3727,22);
                map.put(map1.get("value_ids"),map1.get("sku_id"));
            });
        }
        return map;
    }

    @Override
    @GmallCache(prefix = "index:")
    public List<JSONObject> getBaseCategoryList() {
        //  声明一个集合
        ArrayList<JSONObject> list = new ArrayList<>();
        //  先查询到所有的分类数据
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);

        //  声明一个index
        int index = 1;
        //  先按照一级分类Id进行分组
        //  key = getCategory1Id value = List<BaseCategoryView>
        Map<Long, List<BaseCategoryView>> baseCategory1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //  循环遍历.
        for (Map.Entry<Long, List<BaseCategoryView>> entry : baseCategory1Map.entrySet()) {
            //  获取一级分类Id
            Long category1Id = entry.getKey();
            List<BaseCategoryView> baseCategoryViewList1 = entry.getValue();
            //  声明一个一级分类对象 category1;
            JSONObject category1 = new JSONObject();
            category1.put("index",index);
            category1.put("categoryId",category1Id);
            category1.put("categoryName",baseCategoryViewList1.get(0).getCategory1Name());
            //  category1.put("categoryChild","二级分类集合");
            //  变量迭代
            index++;
            //  以二级分类Id 进行分组
            Map<Long, List<BaseCategoryView>> baseCategory2Map = baseCategoryViewList1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            //  声明一个二级分类对象集合数据
            ArrayList<JSONObject> categoryChild2 = new ArrayList<>();
            //  遍历集合
            for (Map.Entry<Long, List<BaseCategoryView>> entry1 : baseCategory2Map.entrySet()) {
                //  获取二级分类Id
                Long category2Id = entry1.getKey();
                List<BaseCategoryView> baseCategoryViewList2 = entry1.getValue();
                //  声明一个二级分类对象 category2;
                JSONObject category2 = new JSONObject();
                category2.put("categoryId",category2Id);
                category2.put("categoryName",baseCategoryViewList2.get(0).getCategory2Name());
                //  category2.put("categoryChild","三级分类集合");
                categoryChild2.add(category2);
                //  声明一个三级分类对象集合数据
                ArrayList<JSONObject> categoryChild3 = new ArrayList<>();
                //  获取三级分类数据：
                baseCategoryViewList2.forEach(baseCategoryView -> {
                    //  声明一个三级分类对象 category3;
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId",baseCategoryView.getCategory3Id());
                    category3.put("categoryName",baseCategoryView.getCategory3Name());
                    //  将三级分类数据添加到集合中
                    categoryChild3.add(category3);
                });
                //  将三级分类集合添加到二级对象中
                category2.put("categoryChild",categoryChild3);
            }
            //  将二级分类集合添加到一级对象中
            category1.put("categoryChild",categoryChild2);
            //  将一级分类Id 添加到集合中
            list.add(category1);
        }
        //  Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = baseCategory1Map.entrySet().iterator();
        //  返回数据
        return list;
    }

    @Override
    public IPage<SkuInfo> getSkuInfoList(Page<SkuInfo> skuInfoPage, Long category3Id) {
        LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        skuInfoLambdaQueryWrapper.eq(SkuInfo::getCategory3Id,category3Id).orderByDesc(SkuInfo::getId);
        return skuInfoMapper.selectPage(skuInfoPage,skuInfoLambdaQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        //  sku_attr_value
        //  sku_image
        //  sku_info
        //  sku_sale_attr_value
        skuInfoService.save(skuInfo);
        //  sku_image
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)){
            skuImageList.forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
            });

            //  保存数据
            this.skuImageService.saveBatch(skuImageList);
        }

        //  sku_attr_value
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)){
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
            });

            //  批量保存数据
            this.skuAttrValueService.saveBatch(skuAttrValueList);
        }

        //  sku_sale_attr_value
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)){
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            });
            //  批量保存数据
            this.skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);
        }

        //  将布隆过滤器中添加skuId
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);
        bloomFilter.add(skuInfo.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        //        spu_image
        //        spu_info
        //        spu_poster
        //        spu_sale_attr
        //        spu_sale_attr_value
        //  执行insert 之后，spuInfo.getId(); 就会有数据. @TableId(type = IdType.AUTO)
        //  spuInfoMapper.insert(spuInfo);
        spuInfoService.save(spuInfo);
        //  spu_image
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)){
            //  有参有返回
            spuImageList.forEach(spuImage -> {
                //  前端没有传递spuId
                spuImage.setSpuId(spuInfo.getId());
                //  spuImageMapper.insert(spuImage);
            });
            spuImageService.saveBatch(spuImageList);
        }

        //  spu_poster
        //  spuInfo.getSpuPosterList() spuInfo.getSpuImageList() 是如何获取到前端传递的数据！
        //  前端Json 传递的key 与实体类的属性名一样！ spuImageList - spuImageList
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)){
            spuPosterList.forEach(spuPoster -> {
                //  前端没有传递spuId
                spuPoster.setSpuId(spuInfo.getId());
                //spuPosterMapper.insert(spuPoster);
            });
            spuPosterService.saveBatch(spuPosterList);
        }

        //  spu_sale_attr
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)){
            spuSaleAttrList.forEach(spuSaleAttr -> {
                //  前端没有传递spuId
                spuSaleAttr.setSpuId(spuInfo.getId());
                // spuSaleAttrMapper.insert(spuSaleAttr);

                //  spu_sale_attr_value 如何从哪里来? ---传递传递来了，要获取~!
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                //  判断
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)){
                    spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                        //  前端没有传递spuId
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        //  spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
                //  保存销售属性值集合
                spuSaleAttrValueService.saveBatch(spuSaleAttrValueList);
            });
            //  保存销售属性
            spuSaleAttrService.saveBatch(spuSaleAttrList);
        }
    }

    @Override
    public IPage<SpuInfo> getSpuInfoList(Page<SpuInfo> spuInfoPage, Long category3Id) {
        //  select * from spu_info where category3_id = ? limit 2,2;
        LambdaQueryWrapper<SpuInfo> spuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        spuInfoLambdaQueryWrapper.eq(SpuInfo::getCategory3Id,category3Id).orderByDesc(SpuInfo::getId);
        return spuInfoMapper.selectPage(spuInfoPage,spuInfoLambdaQueryWrapper);
    }

    @Override
    public BaseAttrInfo getAttrInfo(Long attrId) {
        //  查询平台属性
        BaseAttrInfo baseAttrInfo = this.baseAttrInfoMapper.selectById(attrId);
        if (baseAttrInfo!=null){
            //  查询平台属性值集合列表
            baseAttrInfo.setAttrValueList(this.getAttrValueList(attrId));
        }
        return baseAttrInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //  修改-保存合并
        if (baseAttrInfo.getId()==null){
            //  base_attr_info 在未保存之前，传递的id 为 null
            //  @TableId(type = IdType.AUTO) 表示当执行完成插入之后，能够获取到主键id 的数据。
            baseAttrInfoMapper.insert(baseAttrInfo);
        } else {
            //  update 语句 base_attr_info
            baseAttrInfoMapper.updateById(baseAttrInfo);
            //  根据平台属性Id 删除平台属性值的数据
            LambdaQueryWrapper<BaseAttrValue> baseAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            baseAttrValueLambdaQueryWrapper.eq(BaseAttrValue::getAttrId,baseAttrInfo.getId());
            //  并不是真正实现的delete 语句，而是执行的是update 语句;
            this.baseAttrValueMapper.delete(baseAttrValueLambdaQueryWrapper);
        }
        //  base_attr_value
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //  判断
        if (!CollectionUtils.isEmpty(attrValueList)){
            //  有参无返回。参数应该是：attrValueList 集合的泛型对象
            attrValueList.forEach(baseAttrValue -> {
                //  attrId = baseAttrInfo.getId 平台属性id
                //  在保存之后，应该获取到当前新增的id 值. 因为@TableId(type = IdType.AUTO) 设置所以id 不为空
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                //  baseAttrValueMapper.insert(baseAttrValue);
                //  insert into base_attr_value values (?,?) (?,?)
            });
            //  批量插入数据
            baseAttrValueService.saveBatch(attrValueList);
        }

    }

    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        //  调用mapper 层
        return baseAttrInfoMapper.selectAttrInfoList(category1Id,category2Id,category3Id);
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        //  创建查询条件
        LambdaQueryWrapper<BaseCategory3> baseCategory3LambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseCategory3LambdaQueryWrapper.eq(BaseCategory3::getCategory2Id,category2Id);
        baseCategory3LambdaQueryWrapper.orderByDesc(BaseCategory3::getId);
        return baseCategory3Mapper.selectList(baseCategory3LambdaQueryWrapper);
    }

    @Override
    public List<BaseCategory1> getCategory1() {
        //  select  * from base_category1;
        return baseCategory1Mapper.selectList(null);
    }
}
